package datastructure;

import java.util.ArrayList;

public class LL1Checker {
	private Grammatica gram;
	private boolean leftRecursive = false;
	private boolean emptySection = true; 
	private boolean emptyStartFollow = true;
	
	public LL1Checker(Grammatica gram) {
		this.gram = gram;
	}
	
	public void defineStarters() {
		gram.defineStarters();
	}

	public void defineFollowers() {
		gram.defineFollowers();
	}
	
	public void checkRuleThree(){
		for(Rule r : gram.getBnf()){
			NonTerminal nonTerminal = r.getNonTerminal();
			for(Alternative a : r.getAlternatives()){
				if(nonTerminal.equals(a.getFirstTerm())){
					leftRecursive = true;
				}
			}
		}
		if(!leftRecursive){
			System.out.println("BNF is correct according to rule 3!");
		}
		else{
			System.out.println("BNF is NOT correct according to rule 3!");
		}
	}
	
	public void checkRuleTwo() {
		for(Rule r : gram.getBnf()){
			ArrayList<Term> starters = r.getStarters();
			ArrayList<Term> followers = r.getFollowers();
			for(Alternative a : r.getAlternatives()){
				if(a.isEmpty()){
					for(Term t : starters){
						if(followers.contains(t)){
							emptyStartFollow = false;
						}
					}
				}
			}
		}
		if(emptyStartFollow){
			System.out.println("BNF is correct according to rule 2!");
		}
		else{
			System.out.println("BNF is NOT correct according to rule 2!");
		}
	}
	
	public void checkRuleOne() {
		for(Rule r : gram.getBnf()) {
			ArrayList<Term> starters = r.getStarters();
			for(Term t : starters) {
				Terminal terminal = (Terminal)t;
				boolean foundSelf = false;
				if(!terminal.isEmpty()) {
					if(starters.contains(terminal)) {
						if(!foundSelf) {
							foundSelf = true;
						} else {
							emptySection = false;
							System.out.println(r.toString() + " is NOT correct according to rule 1!");
						}
					}
				}
			}
		}
		if(emptySection) {
			System.out.println("BNF is correct according to rule 1!");
		}
	}

	public void checkLL1() {
		System.out.println("===========================");
		System.out.println("=     CHECKING FOR LL1    =");
		System.out.println("===========================");
		System.out.println();
		System.out.println("---------------------------");
		System.out.println("-          RULE 1         -");
		System.out.println("---------------------------");
		checkRuleOne();
		System.out.println("---------------------------");
		System.out.println("-          RULE 2         -");
		System.out.println("---------------------------");
		checkRuleTwo();
		System.out.println("---------------------------");
		System.out.println("-          RULE 3         -");
		System.out.println("---------------------------");
		checkRuleThree();
	}
}
